'use strict';
var EventEmitter = require('events').EventEmitter;

class PubSub extends EventEmitter {
    constructor() {
        super();
        this.sub = {};

    }

    publish(eventType, data) {
        this.emit('newMsg', eventType, data);
    }

    subscribe(eventType, handler) {
        if (!this.sub[eventType]) this.sub[eventType] = [];
        this.sub[eventType].push(handler);
    }

    handleMsg(eventType, data) {
        let handlers = this.sub[eventType];
        for (var handler of handlers) {
            handler(data);
        }
    }

}

let pubsub = new PubSub();

pubsub.on('newMsg', function(eventType, data) {
    let self = this;
    process.nextTick(function() {
        self.handleMsg(eventType, data);
    });
});


module.exports = pubsub;